/*
* //用来新建/调整价目表
*/
public without sharing class PriceListController {
	

	public Boolean isSelect {get;set;}//是否在选择界面

	public String accId {get;set;}//客户id
	public String adjustId {get;set;}//调整Id

	public Boolean isErr {get;set;}
	public String  msg {get;set;}
	public Boolean isSuccess {get;set;}

	public String paramJson {get;set;}//传参数
	public String searchJson {get;set;}//检索用的参数
	public String resJson {get;set;}//保存用
	public AdjustPrice__c  ap {get;set;}//

	public String parentId { get;private set;}//体系客户ID

    public Boolean isGPO { get;private set;}//是否是gpo客户

	public Boolean isSys {get;set;}//是否为三方体系
    public Boolean isBM {get;set;}//是否为大家体系

	public String pname {get;set;}//产品名称
	public String pserialNo {get;set;}//产品货号
	public String pnccode {get;set;}//产品存货编码
	public String pspec {get;set;}//规格
	public String pmodel {get;set;}//型号
	public String pbrand {get;set;}//品牌
	public String pcategory1 {get;set;}//产品一级分类
	public String pcategory0 {get;set;}//产品主分类
	public String productType {get;set;}//产品类型
    public String papplication ;
    public String aplicableInstrumentcombbox {get;private set;}

	public String lastMothOpt {get;set;}//判断 > < = no  上月平均价

	public Boolean isNew ;//是新建还是编辑

	public String company {get;set;}//公司
    public String province {get;private set; }
	public String dataOpts {get;private set;}
    public Boolean isCouldFindOverseaProduct;
    public Boolean isLookInvoiceDealerPrice{get;private set;}

    public Boolean isDealer {get;private set;}

    public class ControllerException extends Exception {}

	public PriceListController(ApexPages.StandardController con){
		 // dataOpts = 'FromProduct;ParentProduct;PriceProduct';
		resJson = '[]';
		isSelect = true;
		isNew = false;
		isErr =false;
        accId = System.currentPageReference().getParameters().get('accId');
        adjustId = System.currentPageReference().getParameters().get('id');
	}
    public PriceListController() {
    	
    }
    //是否为第三方客户
    private boolean isThrid(Account acc ){
        if(acc == null)return false;
        if(acc.System__c != null) return true;
        return false;
    }
    //是否为大家
    private boolean checkIsBM(Account acc){
        return  acc.ParentId != null && acc.System__c == '大家检验';
    }
    public void init(){
    	System.debug('***'+accId + '***'+adjustId);
    	System.debug(ap);
         User u = [select Profile.Name ,PriceProvince__c ,SubCompany__c from User where Id = :UserInfo.getUserId()];
        isCouldFindOverseaProduct = u.Profile.Name.contains('海外') ? true : false;
        isLookInvoiceDealerPrice  = u.Profile.Name != '销售部直销销售员';
        try{
            Account acc  = null;
            if(adjustId != null){///编辑

                 ap = [select Id ,Status__c,ApplicableCustomers__c,OwnerId,EffectiveDateFrom__c  ,SalesCode__c,Account__c,Account__r.RecordType.DeveloperName , Company__c,Reason__c,Account__r.ParentId from  AdjustPrice__c where Id =:adjustId];
                if(ap == null )throw new DmlException('页面打开错误!');

                if(ap.Status__c == '已提交' || ap.Status__c == '已批准')throw new DmlException(ap.Status__c+'中不能修改!');
                    
                parentId = ap.Account__r.ParentId; 
                
                province = [select PriceProvince__c from User where Id=:ap.OwnerId].PriceProvince__c;
                accId = ap.Account__c;
                isDealer = ap.Account__r.RecordType.DeveloperName == 'Dealer' ;
                acc = [select Id,ParentId,RecordType.DeveloperName,Parent.AccountNumber,System__c  from Account where Id=:accId];

            }else{
                if(accId != null){
                     acc = [select Id,ParentId,RecordType.DeveloperName,Parent.AccountNumber,System__c   from Account where Id=:accId];
                    if(acc == null )throw new DmlException('页面打开错误!');
                       
                    parentId = acc.ParentId; 

                    isDealer = acc.RecordType.DeveloperName == 'Dealer' ;
                    ap = new AdjustPrice__c(Account__c = acc.Id , Status__c = '草案中');
                    ap.ApplicableCustomers__c = acc.Id ;// isDealer ? null : acc.Id ; 
                    province =u.PriceProvince__c;

                }else{
                    throw new DmlException('页面打开错误!');
                    
                }

                isNew = true;
            }

            isGPO = acc.Parent.AccountNumber  == '301133';
            aplicableInstrumentcombbox = getOptMap(ImportObject.getPicklistValues('Product__c', 'ApplicableInstrumentModel__c', true));

            if(ap.Company__c == null) {
                 ap.Company__c = u.SubCompany__c;
                
            }

            

            isSys = isThrid(acc); 
            isBM = checkIsBM(acc);
            if(!isSys && !isGPO){
                dataOpts = 'FromProduct;PriceProduct';
            }else{
                dataOpts = 'FromProduct;ParentProduct;PriceProduct';
            }

            setCreidt();



        }catch(Exception e ){
            isErr = true;
                ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));
        }
        
    	
 
    }

    public String getOptMap(Map<String,String> opts){
       Map<String ,Object> cooMap = new Map<String ,Object> ();
      cooMap.put('valueField', 'value');
      cooMap.put('textField', 'label');
      cooMap.put('panelHeight', 'auto');
      cooMap.put('limitToList', 'true');
      List<Map<String,String>>  dList = new List<Map<String,String>>();
      for (String k : opts.keySet()) {
        Map<String ,String> dataMap = new Map<String,String>();
        dataMap.put('label',opts.get(k) );
        dataMap.put('value',k );
        dList.add(dataMap);
      }  
      cooMap.put('data', dList);   
      
      return EncodingUtil.urlEncode(JSON.serialize(cooMap), 'UTF-8');
    }

    public void nextstep(){

    }
    ///带入客户下的信用期信用额 设置 记录类型
    public void setCreidt(){
       List<AccountCredit__c> accCredit =  [select Id ,CreditLimit__c, NCCreditDeadline__c from AccountCredit__c where Account__c =:accId and Company__c =:ap.Company__c limit 1];
       if(accCredit != null && accCredit.size() != 0 ){
            ap.NCCreditLimit__c = accCredit[0].CreditLimit__c;
            ap.NCCreditDeadline__c = accCredit[0].NCCreditDeadline__c;
        }
        Account acc = [select Id,RecordType.DeveloperName from Account where Id=:accId];
        ap.RecordTypeId = acc.RecordType.DeveloperName == 'TerminalCustomer' ? Utils.getRecordTypeIdByDevNameAndObjName('TerminalCustomerAdjustPrice', 'AdjustPrice__c'): Utils.getRecordTypeIdByDevNameAndObjName('DealerAdjustPrice', 'AdjustPrice__c');
    }
    ///获取已经有调价明细
    public void getDetails(){
	    List<AdjustPriceBean> tmp = new List<AdjustPriceBean>();
        System.debug('获取明细'+ap);
    	if(ap.Id != null ){
            //isFromSystem__c
    		 List<AdjustPriceProduct__c> apList = [select Id,Product__c,Product__r.ProductName__c ,Product__r.Name,Product__r.Brand__c,Product__r.Model__c,ProductLine__c,
    			Product__r.Category1__c,Product__r.Unit__c,Product__r.Category2__c,Product__r.Category0__c,Product__r.zl__c,Product__r.TypeName__c,Product__r.ApplicableInstrumentModel__c,
                Product__r.GroupRegionalDistributorsPrice__c,Product__r.GroupTerminalGuidePric__c,Product__r.GroupMarketPrice__c,Product__r.GroupSpecialPrice__c,Product__r.GroupProvincialAgencyPrice__c,Product__r.GroupDeclarationDealerPrice__c,

    			Product__r.NCCode__c,Product__r.SerialNo__c,Product__r.Spec__c,AreaDealerPrice__c,OriginalPrice__c,InstCost__c,QuotoReason__c,
    			InvoiceDealerPrice__c,HospitalManagerPrice__c,AdjustSalesPrice__c,CompanyBottomPrice__c,SystemPrice__c
    		 from AdjustPriceProduct__c where AdjustPrice__c =:ap.Id ];
    		 if(apList == null || apList.size() == 0)return;
    		 Set<Id>  pset= new Set<Id>();

             Set<Id> maccuras = new Set<Id>();
    		for(AdjustPriceProduct__c  app : apList){
    			pset.add(app.Product__c);
                if(MaccuraBrandUtil.maccura.contains(app.Product__r.Brand__c))maccuras.add(app.Product__c);
    		}

            System.debug(ap.Company__c+' '+province);

    		Map<Id,Price__c> prMap = ImportObject.getPriceMap(pset, ap.Company__c,province );
            Map<Id,Price__c> maccuraPrMap = !isSys || maccuras.isEmpty() ? new  Map<Id,Price__c>():   ImportObject.getPriceMap(maccuras, '迈克生物股份有限公司',false);

           // String companyName =  !isGPO&& isSys  ? '迈克生物股份有限公司':ap.Company__c;
            //Map<Id,Price__c> prMap = !isGPO&& isSys  ? ImportObject.getPriceMap(pset,companyName) : ImportObject.getPriceMap(pset,companyName,province);
            System.debug(ap.Company__c+' '+prMap);

    		Map<Id,AveragePrice__c> lastprMap  = ImportObject.getLastMothPrice(pset, ap.Company__c,province);

    		Map<Id,PriceList__c> priceListMap = ImportObject.getPriceListMap(pset, accId,ap.ApplicableCustomers__c, ap.SalesCode__c, ap.Company__c,false);

    		Map<Id,PriceList__c> syspriceListMap = ImportObject.getPriceListMap(pset, ParentId, ap.SalesCode__c, ap.Company__c,true);

            for(AdjustPriceProduct__c p :apList){
	    		tmp.add(new AdjustPriceBean(p,prMap.get(p.Product__c),lastprMap.get(p.Product__c),priceListMap.get(p.Product__c),syspriceListMap.get(p.Product__c),isSys));

	    	}
    	}

    		paramJson = EncodingUtil.urlEncode(JSON.serialize(tmp),	 'UTF-8');
            System.debug(paramJson);
    	

    }
    ///保存数据
    public void save (){
    	msg = '';
    	System.debug('**'+resJson);
    	List<Object> resList=(List<Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(resJson, 'UTF-8'));
    		
    	if(resList.size() == 0){
    		msg = '保存失败,没有数据!';
    		return;
    	}
    	//Set<String>  pros= getExistProdcut(accId,false);
    	//System.debug('***'+pros);
    	SavePoint sp = Database.setSavepoint();
    	try {
    		System.debug('***' + ap);
    		if(isNew)ap.Id = null ;
    		System.debug('***' + ap);
    		upsert ap;
    		System.debug('***' + ap);

    		Set<String> prosets = new Set<String>();
	    	List<AdjustPriceProduct__c> apList = new List<AdjustPriceProduct__c>();
	    	for (Object res : resList) {
	    		Map<String ,Object> o = (Map<String ,Object> )res;
	    		AdjustPriceProduct__c app = new AdjustPriceProduct__c();
	    		
	    		String productId = o.get('productId') == null ? null : String.valueOf(o.get('productId'));
	    		if(productId == null ){
	    			msg = o.get('productName') +'的产品ID为空,不能保存!';
	    			break;
	    		}else{
	    			prosets.add(productId);
	    			app.Product__c = productId;
	    		}
	    		if(o.get('productName') != null ){
	    			app.Name = String.valueOf(o.get('productName'));
                    if(app.Name.length() > 80) app.Name =app.Name.substring(0,80);
	    		}
                if(o.get('cate0') != null && String.valueOf(o.get('cate0')) == '仪器' ){
                    msg = o.get('productName')+ ':仪器类产品不能建立价目表!';
                    break;
                }
	    		if(o.get('adprice') != null ){
	    			app.AdjustSalesPrice__c =getValue(o.get('adprice'));
	    		}else{
		    		msg = o.get('productName')+ '产品的新增价格必填!';
		    		break;
	    				
	    		}

                if(o.get('provincialAgencyPrice') != null ) app.ProvincialAgencyPrice__c =  getValue(o.get('provincialAgencyPrice'));
	    		if(o.get('price') != null ){
	    			app.OriginalPrice__c = getValue(o.get('price'));
	    		}
                

	    		if(o.get('invoiceDealerPrice') != null ){
	    			app.InvoiceDealerPrice__c = getValue(o.get('invoiceDealerPrice'));
	    		}

	    		if(o.get('areaDealerPrice') != null ){
	    			app.AreaDealerPrice__c = getValue(o.get('areaDealerPrice'));
	    		}

               // app.isFromSystem__c = Boolean.valueOf(o.get('isFromsys')) ;
                Decimal sysPrice = getValue(o.get('sysPrice'));
                app.InstCost__c = getValue(o.get('instCost'));

                if((app.InstCost__c == null || app.InstCost__c == 0 )&& (sysPrice == null || sysPrice == 0 )   ){

                        msg += o.get('productName') +'--' + o.get('nccode') +',没有成本价!\n请联系子公司维护价格体系人员处理！';
                    
                } 

                if(!isGPO && o.get('sysPrice') != null){
                    app.SystemPrice__c =  sysPrice;
                }

    	   

	    		if(o.get('companyBottomPrice') != null ){
	    			app.CompanyBottomPrice__c = getValue(o.get('companyBottomPrice'));
	    		}
	    		if(o.get('hospitalManagerPrice') != null ){
	    			app.HospitalManagerPrice__c = getValue(o.get('hospitalManagerPrice'));
	    		}
	    		if(o.get('lastMothPrice') != null ){
	    			app.LastMonthAveragePrice__c = getValue(o.get('lastMothPrice'));
	    		}
	    		 
                if(o.get('reason') != null){
                    app.QuotoReason__c = String.valueOf(o.get('reason'));
                }
                if(o.get('productline') != null){
                    app.ProductLine__c = String.valueOf(o.get('productline'));
                }
                if(o.get('specialprice') != null ){
                    app.SpecialPrice__c = getValue(o.get('specialprice'));
                }
                if(isGPO && o.get('sysPrice')!= null )app.GPOPrice__c = sysPrice;
	    		app.AdjustPrice__c = ap.Id;

	    		apList.add(app);


	    	}
            if(msg.length() > 0) return;
	    	///验证价目表中是否存在调价的产品
    		System.debug('***' + apList);
	    	
	    	List<AdjustPriceProduct__c> deleList = [select Id from AdjustPriceProduct__c where AdjustPrice__c =: ap.Id];
	    	if(deleList != null && deleList.size() > 0) delete deleList;
	    	insert apList;
            msg = '保存成功!';
    	    isSuccess = true;
    	}catch(Exception e) {
    	    Database.rollback(sp);
    	    isSuccess = false;
    	    System.debug('***'+e);
    	    msg = '保存失败!' +e.getMessage();

    	}
    	

    }
    private Decimal getValue(Object val){
        if(val == null)return null;
        String  d = String.valueOf(val);
        if(d == '')return null;
        return Decimal.valueOf(d.trim());
    }

    ///从产品中选择 //如果是第三方体系 则要排除系统中部中的产品
    public void getProduct(){

    	System.debug('***'+ap.Company__c);
    	//System.debug('***'+ImportObject.getPicklistValues('Contract__c','Corpcode__c',false));
        //String companyName =  !isGPO&& isSys  ? '迈克生物股份有限公司':ap.Company__c;

    	String companycode = ImportObject.getPicklistValues('Contract__c','Corpcode__c',false).get(ap.Company__c);

    	String sealflag  =  'Y-'+ companycode;

    	String sql = 'select Id,Name,Unit__c,ProductName__c ,brand__c,Spec__c ,SerialNo__c ,Model__c ,NCCode__c,Category1__c,Category2__c,Category0__c,zl__c,SealCompany__c ,TypeName__c,ApplicableInstrumentModel__c ,';
        sql+='GroupRegionalDistributorsPrice__c,GroupTerminalGuidePric__c,GroupMarketPrice__c,GroupSpecialPrice__c,GroupProvincialAgencyPrice__c,GroupDeclarationDealerPrice__c';
    	 sql += ' from Product__c where  RecordType.DeveloperName = \'NCProduct\' and NCCode__c != null and PriceCompany__c like \'%'+companycode+'%\'  and Category0__c !=\'仪器\' ';
        if(!isCouldFindOverseaProduct ) sql += ' and Overseasproducts__c != true ';

        if(isBM ){

            sql += ' and Brand__c  not in '+ MaccuraBrandUtil.getMaccuraInStr() + '  and   NCCode__c not in ' + MaccuraBrandUtil.getMaccuraInStr()  ;

        }


        if(String.isBlank(pname) == false ) sql += ' and Name like \'%'+pname+'%\' ';
    	 if(String.isBlank(pbrand) == false ) sql += '  and Brand__c like \'%'+pbrand+'%\' ';
    	 if(String.isBlank(pspec) == false ) sql += '  and Spec__c like \'%'+pspec+'%\' ';
    	 if(String.isBlank(pnccode) == false ) sql += '  and NCCode__c like \'%'+pnccode+'%\' ';
    	 if(String.isBlank(pcategory0) == false ) sql += '  and Category0__c like \'%'+pcategory0+'%\' ';
    	 if(String.isBlank(pcategory1) == false ) sql += '  and Category1__c like \'%'+pcategory1+'%\' ';
    	 if(String.isBlank(pserialNo) == false ) sql += '  and SerialNo__c like \'%'+pserialNo+'%\' ';
    	 if(String.isBlank(productType) == false ) sql += '  and TypeName__c like \'%'+productType+'%\' ';
         if(String.isBlank(papplication) == false ) sql += '  and ApplicableInstrumentModel__c includes (\''+papplication+'\') ';


    	 sql +=' limit 300 ';


    	List<Product__c>pList = Database.query(sql);
    	List<AdjustPriceBean> tmp = new List<AdjustPriceBean>();
    	if(pList == null || pList.size() == 0){
 	    	paramJson = EncodingUtil.urlEncode(JSON.serialize(tmp),	 'UTF-8');
    	 	return;
    	 }
    	Set<Id>  pids= new Set<Id>();

       
        Set<Id>  maccuras= new Set<Id>();

    	for(Product__c p :pList){
    		if(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag)) continue;
    		pids.add(p.Id);
            if(MaccuraBrandUtil.maccura.contains(p.Brand__c))maccuras.add(p.Id);
    	}

       // Map<Id,Price__c> prMap = !isGPO&& isSys  ? ImportObject.getPriceMap(pids,companyName) : ImportObject.getPriceMap(pids,companyName,province);

    	Map<Id,Price__c> prMap =ImportObject.getPriceMap(pids, ap.Company__c,province);
        Map<Id,Price__c> maccuraPrMap = !isSys || maccuras.isEmpty() ? new  Map<Id,Price__c>():   ImportObject.getPriceMap(maccuras, '迈克生物股份有限公司',false);

        Map<Id,AveragePrice__c> lastprMap  = ImportObject.getLastMothPrice(pids, ap.Company__c,province);
    	Map<Id,PriceList__c> priceListMap = ImportObject.getPriceListMap(pids,ap.Account__c,ap.ApplicableCustomers__c,ap.SalesCode__c, ap.Company__c,false);
    	Map<Id,PriceList__c> sysPriceListMap = new Map<Id,PriceList__c>();

    	if(parentId != null) sysPriceListMap = ImportObject.getPriceListMap(pids, parentId,ap.SalesCode__c, ap.Company__c,true);

    	for(Product__c p :pList){
    		if(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag)) continue;
    		if(prMap.get(p.Id) == null) continue;
    		tmp.add(new AdjustPriceBean(p,maccuraPrMap.containsKey(p.Id) ? maccuraPrMap.get(p.Id) :  prMap.get(p.Id),lastprMap.get(p.Id),priceListMap.get(p.Id),sysPriceListMap.get(p.Id),isSys));

    	}
    	
    	paramJson = EncodingUtil.urlEncode(JSON.serialize(tmp),	 'UTF-8');

    }
  

    ///从价目表中选择
    public void getProductFromPriceList(String acId ,Boolean isParent ){

    	String companycode = ImportObject.getPicklistValues('Contract__c','Corpcode__c',false).get(ap.Company__c);
    	String sealflag  =  'Y-'+ companycode;
    	String sql = 'select Product__c,Product__r.Unit__c,Product__r.Brand__c,Product__r.Spec__c,Product__r.SerialNo__c,Product__r.Model__c ,';
    		sql += 'Product__r.Category1__c,Product__r.Category2__c,Product__r.Category0__c,Product__r.zl__c,Product__r.NCCode__c,';
            sql+='Product__r.GroupRegionalDistributorsPrice__c,Product__r.GroupTerminalGuidePric__c,Product__r.GroupMarketPrice__c,Product__r.GroupSpecialPrice__c,Product__r.GroupProvincialAgencyPrice__c,Product__r.GroupDeclarationDealerPrice__c,';

    		sql += 'Product__r.ProductName__c,Product__r.Name,SalesCode__c,Price__c,Id,Product__r.SealCompany__c ,Product__r.TypeName__c,Product__r.ApplicableInstrumentModel__c from PriceList__c ';

    		sql += ' where Account__c =\''+acId+'\' ';
            if(!isCouldFindOverseaProduct ) sql += ' and Product__r.Overseasproducts__c != true ';
            if(isBM ){

                sql += ' and Product__r.Brand__c  not in '+ MaccuraBrandUtil.getMaccuraInStr() + '  and   Product__r.NCCode__c not in ' + MaccuraBrandUtil.getMaccuraInStr()  ;
                
            }


    		if(!isParent)sql +=' and  SalesCode__c=\''+ap.SalesCode__c+'\' and Company__c = \''+ap.Company__c+'\'  ' ;
            if(ap.ApplicableCustomers__c != null &&  ap.ApplicableCustomers__c != acId && !isParent )sql  += ' and ApplicableCustomers__c =\''+ap.ApplicableCustomers__c+'\'' ;
            if(ap.ApplicableCustomers__c != null &&  ap.ApplicableCustomers__c == acId && !isParent )sql  += ' and (ApplicableCustomers__c =\''+ap.ApplicableCustomers__c+'\'  or  ApplicableCustomers__c = null ) ' ;

    		System.debug('***'+sql);
    	
    	 
    	 if(String.isBlank(pname) == false ) sql += ' and Product__r.ProductName__c like \'%'+pname+'%\' ';
    	 if(String.isBlank(pbrand) == false ) sql += '  and Product__r.Brand__c like \'%'+pbrand+'%\' ';
    	 if(String.isBlank(pspec) == false ) sql += '  and Product__r.Spec__c like \'%'+pspec+'%\' ';
    	 if(String.isBlank(pnccode) == false ) sql += '  and Product__r.NCCode__c like \'%'+pnccode+'%\' ';
    	 if(String.isBlank(pcategory0) == false ) sql += '  and Product__r.Category0__c like \'%'+pcategory0+'%\' ';
    	 if(String.isBlank(pcategory1) == false ) sql += '  and Product__r.Category1__c like \'%'+pcategory1+'%\' ';
    	 if(String.isBlank(pserialNo) == false ) sql += '  and Product__r.SerialNo__c like \'%'+pserialNo+'%\' ';
         if(String.isBlank(papplication) == false ) sql += '  and Product__r.ApplicableInstrumentModel__c includes (\''+papplication+'\') ';

    	 System.debug('-->' +sql);
    	 List<PriceList__c> pList = Database.query(sql);
    	List<AdjustPriceBean> tmp = new List<AdjustPriceBean>();
    	 if(pList == null || pList.size() == 0){
 	    	paramJson = EncodingUtil.urlEncode(JSON.serialize(tmp),	 'UTF-8');
    	 	return;
    	 }
    	 Set<Id>  pids = new Set<Id>();
         Set<Id>  maccuras = new Set<Id>();

    	 for (PriceList__c p : pList) {
    	 	 if(p.Product__r.SealCompany__c != null && p.Product__r.SealCompany__c.contains(sealflag)) continue;

    	 	pids.add(p.Product__c);
            if(MaccuraBrandUtil.maccura.contains(p.Product__r.Brand__c))maccuras.add(p.Product__c);
    	 }

   		//String companyName =  !isGPO&& isSys  ? '迈克生物股份有限公司':ap.Company__c;

    	//Map<Id,Price__c> prMap = !isGPO&& isSys  ? ImportObject.getPriceMap(pids,companyName) : ImportObject.getPriceMap(pids,companyName,province);
        Map<Id,Price__c> prMap =  ImportObject.getPriceMap(pids,ap.Company__c,province);
        Map<Id,Price__c> maccuraPrMap = !isSys || maccuras.isEmpty() ? new  Map<Id,Price__c>():   ImportObject.getPriceMap(maccuras, '迈克生物股份有限公司',false);
        Map<Id,AveragePrice__c> lastprMap  = ImportObject.getLastMothPrice(pids,ap.Company__c,province);
    	Map<Id,PriceList__c> sysPriceListMap = new Map<Id,PriceList__c>();
        
        System.debug('销售员所属公司:'+ap.Company__c);

    	if(parentId != null) sysPriceListMap = ImportObject.getPriceListMap(pids, parentId,ap.SalesCode__c, ap.Company__c,true);
    	for(PriceList__c p :pList){
    	 	 if(p.Product__r.SealCompany__c != null && p.Product__r.SealCompany__c.contains(sealflag)) continue;
    			AveragePrice__c ap = lastprMap.get(p.Product__c);
    		if(lastMothOpt != null && lastMothOpt != ''){
    			if(lastMothOpt == '<' && (ap == null || ap.AveragePrice__c == null  || ap.AveragePrice__c <= p.Price__c ))continue;///低于
	            if(lastMothOpt == '>' && (ap == null || ap.AveragePrice__c == null  ||  ap.AveragePrice__c >= p.Price__c ))continue;///高于
	            if(lastMothOpt == 'no' && (ap != null && ap.AveragePrice__c != null) ) continue;///为空
	            if(lastMothOpt == '=' && (ap == null ||  ap.AveragePrice__c != p.Price__c ))continue;///等于
	    		
	    	}
    		tmp.add(new AdjustPriceBean(p,maccuraPrMap.containsKey(p.Product__c) ? maccuraPrMap.get(p.Product__c) : prMap.get(p.Product__c),ap,sysPriceListMap.get(p.Product__c),isSys));
    	}
    	


    	paramJson = EncodingUtil.urlEncode(JSON.serialize(tmp),	 'UTF-8');
    }
    ///检索..产品...
    public void search(){
    	pname = '';
    	pbrand = '';
    	pspec = '';
    	pnccode = '';
    	pserialNo = '';
    	pcategory0 = '';
    	pcategory1 = '';
    	lastMothOpt = '';
    	productType = '';
        papplication = '';
        
    	System.debug('***'+searchJson); 
    	System.debug('***'+EncodingUtil.urlDecode(searchJson, 'UTF-8')); 
    	Map<String,Object> searchMap =(Map<String,Object> )JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson, 'UTF-8'));
    	String type = String.valueOf(searchMap.get('type')) ;
    	String productName =  String.valueOf(searchMap.get('productName')) ;
		String brand =  String.valueOf(searchMap.get('brand')) ;
		String spec =  String.valueOf(searchMap.get('spec') );
		String cate0 =  String.valueOf(searchMap.get('cate0')) ;
		String nccode =  String.valueOf(searchMap.get('nccode')) ;
		String cate1=  String.valueOf(searchMap.get('cate1') );
		String serialNo=  String.valueOf(searchMap.get('serialNo') );
		 lastMothOpt=  String.valueOf(searchMap.get('lastMothOpt') );
		String ptype=  String.valueOf(searchMap.get('ptype') );


		if( productName != null && productName != '')pname = productName;
		if( brand != null && brand != '')pbrand = brand;
		if( spec != null && spec != '')pspec = spec;
		if( cate0 != null && cate0 != '')pcategory0 = cate0;
		if( cate1 != null && cate1 != '')pcategory1 = cate1;
		if( nccode != null && nccode != '')pnccode = nccode;
		if( serialNo != null && serialNo != '')pserialNo = serialNo;
		if( ptype != null && ptype != '')productType = ptype;
        if(String.isNotBlank(String.valueOf(searchMap.get('application')))) papplication = String.valueOf(searchMap.get('application'));


    	if(type == 'FromProduct'){//从产品中选择
			getProduct();
    	}else if(type == 'ParentProduct'){//体系价目表中选择
			getProductFromPriceList(String.valueOf(parentId),true);

    	}else if(type == 'PriceProduct'){//从价目表中选择
			getProductFromPriceList(accId,false);

    	}


    }

    ///置空参数
    public void setNil(){
    	paramJson = '';
    	searchJson = '';
    	resJson = '[]';
    	pname = '';
    	pbrand = '';
    	pspec = '';
    	pnccode = '';
    	pcategory0 = '';
    	pcategory1 = '';
    }

    //中间Bean 
    public class  AdjustPriceBean{
    	public String productId {get;set;}//产品ID
    	public String productName {get;set;}//产品名称
    	public String brand {get;set;}//品牌
    	public String  spec {get;set;}//规格
    	public String  serialNo {get;set;}//货号
    	public String  model {get;set;}//型号
    	public String  nccode {get;set;}//存货编码
        public String unit; 

    	public String  productType {get;set;}//产品类型

    	public Decimal price {get;set;}//单价
    	public Decimal sysPrice {get;set;}//第三方体系价

    	public Decimal adprice {get;set;} //调整价格
    	public Decimal discount {get;set;}//折扣率

    	public String cate0 {get;set;}//主分类
    	public String cate1 {get;set;}//一级分类
    	public String cate2 {get;set;}//二级分类

    	public String zl  {get;set;}//装量
    	public Decimal taxrate {get;set;}//税率
        public String application;

    	public Decimal companyBottomPrice {get;set;}//公司底价
    	public Decimal areaDealerPrice {get;set;}//区域经销商价
    	public Decimal instCost {get;set;}//成本价
    	public Decimal invoiceDealerPrice {get;set;}//报价经销商价
    	public Decimal hospitalManagerPrice {get;set;}//终端指导价
        public Decimal provincialAgencyPrice ;
    	public Decimal marketPrice {get;set;}//市场报价

    	public Boolean isHasLastMothPrice {get;set;}//是否有上月平均价
    	public Decimal lastMothPrice {get;set;}//上月平均价

    	public Decimal adjustPrice {get;set;}//调整价
        public Boolean isFromsys {get;set;}//是否来自价格体系



        public String reason {get;set;}//报价原因
        public String productline {get;set;}//产品线
        public Decimal specialprice ;


    	public AdjustPriceBean(Product__c p,Price__c pr,AveragePrice__c ap,PriceList__c pl ,PriceList__c syspl , Boolean isSys ){
    		productId = p.Id ;
    		productName = p.ProductName__c == null ?  p.Name:p.ProductName__c ;
    		spec = p.Spec__c;
    		model = p.Model__c;
    		serialNo = p.SerialNo__c;
            unit = p.Unit__c;
    		nccode = p.NCCode__c;
    		brand = p.Brand__c;
    		cate0 = p.Category0__c;
    		cate1 = p.Category1__c;
    		cate2 = p.Category2__c;
            productline = p.Category1__c;
    		zl = p.zl__c;
            isFromsys = syspl != null ;
    		productType = p.TypeName__c;
            application = p.ApplicableInstrumentModel__c;
    		if(pr == null )pr = new Price__c();

			taxrate  = pr.Taxrate__c;
			companyBottomPrice = pr.CompanyBottomPrice__c;
    		// 	areaDealerPrice = pr.AreaDealerPrice__c;
    		// 	instCost = pr.InstCost__c;
    		// 	invoiceDealerPrice = pr.InvoiceDealerPrice__c;
    		// 	hospitalManagerPrice = pr.HospitalManagerPrice__c;
    		// 	marketPrice = pr.MarketPrice__c;
      //           specialprice = pr.SpecialPrice__c;
      //           provincialAgencyPrice = pr.ProvincialAgencyPrice__c;

    		// }
            areaDealerPrice =isSys && MaccuraBrandUtil.maccura.contains(brand) ? p.GroupRegionalDistributorsPrice__c :  pr.AreaDealerPrice__c;
            instCost =  pr.InstCost__c;
            invoiceDealerPrice = isSys && MaccuraBrandUtil.maccura.contains(brand) ? p.GroupDeclarationDealerPrice__c : pr.InvoiceDealerPrice__c;
            hospitalManagerPrice =isSys && MaccuraBrandUtil.maccura.contains(brand) ? p.GroupTerminalGuidePric__c :  pr.HospitalManagerPrice__c;
            marketPrice =isSys && MaccuraBrandUtil.maccura.contains(brand) ? p.GroupMarketPrice__c :  pr.MarketPrice__c;
            specialprice = isSys && MaccuraBrandUtil.maccura.contains(brand) ? p.GroupSpecialPrice__c : pr.SpecialPrice__c;
            provincialAgencyPrice =isSys && MaccuraBrandUtil.maccura.contains(brand) ? p.GroupProvincialAgencyPrice__c :  pr.ProvincialAgencyPrice__c;
            
    		if(pl != null)price = pl.Price__c;
    		if(syspl != null)sysPrice = syspl.Price__c;
    		isHasLastMothPrice = ap != null;
    		if(ap != null )lastMothPrice = ap.AveragePrice__c;	


    	}
    	public AdjustPriceBean(PriceList__c p,Price__c pr,AveragePrice__c ap,PriceList__c syspl,Boolean isSys){
    		productId = p.Product__c;
    		productName =  p.Product__r.ProductName__c == null ?  p.Product__r.Name:p.Product__r.ProductName__c ; //p.Product__r.Name;
    		spec = p.Product__r.Spec__c;
    		model = p.Product__r.Model__c;
            unit = p.Product__r.Unit__c;

    		serialNo = p.Product__r.SerialNo__c;
    		nccode = p.Product__r.NCCode__c;
    		brand = p.Product__r.Brand__c;
            productline = p.Product__r.Category1__c;
            application = p.Product__r.ApplicableInstrumentModel__c;
    		cate0 = p.Product__r.Category0__c;
    		cate1 = p.Product__r.Category1__c;
    		cate2 = p.Product__r.Category2__c;
    		zl =p.Product__r.zl__c;
            isFromsys = syspl != null;
    		productType = p.Product__r.TypeName__c;
    		if(!isSys)price = p.Price__c;
    		if(syspl != null)sysPrice = syspl.Price__c;
    		if(pr == null )pr = new Price__c();
			taxrate  = pr.Taxrate__c;
			companyBottomPrice = pr.CompanyBottomPrice__c;
    		// 	areaDealerPrice = pr.AreaDealerPrice__c;
    		// 	instCost = pr.InstCost__c;
    		// 	invoiceDealerPrice = pr.InvoiceDealerPrice__c;
    		// 	hospitalManagerPrice = pr.HospitalManagerPrice__c;
    		// 	marketPrice = pr.MarketPrice__c;
      //           specialprice = pr.SpecialPrice__c;
      //           provincialAgencyPrice = pr.ProvincialAgencyPrice__c;
    		// }
            areaDealerPrice =isSys && MaccuraBrandUtil.maccura.contains(brand) ? p.Product__r.GroupRegionalDistributorsPrice__c :  pr.AreaDealerPrice__c;
            instCost =  pr.InstCost__c;
            invoiceDealerPrice = isSys && MaccuraBrandUtil.maccura.contains(brand) ? p.Product__r.GroupDeclarationDealerPrice__c : pr.InvoiceDealerPrice__c;
            hospitalManagerPrice =isSys && MaccuraBrandUtil.maccura.contains(brand) ? p.Product__r.GroupTerminalGuidePric__c :  pr.HospitalManagerPrice__c;
            marketPrice =isSys && MaccuraBrandUtil.maccura.contains(brand) ? p.Product__r.GroupMarketPrice__c :  pr.MarketPrice__c;
            specialprice = isSys && MaccuraBrandUtil.maccura.contains(brand) ? p.Product__r.GroupSpecialPrice__c : pr.SpecialPrice__c;
            provincialAgencyPrice =isSys && MaccuraBrandUtil.maccura.contains(brand) ? p.Product__r.GroupProvincialAgencyPrice__c :  pr.ProvincialAgencyPrice__c;
            
    		isHasLastMothPrice = ap !=  null;
    		if(ap != null )lastMothPrice = ap.AveragePrice__c;
    	}

    	public AdjustPriceBean(AdjustPriceProduct__c p,Price__c pr,AveragePrice__c ap ,PriceList__c pl,PriceList__c syspl ,Boolean isSys ){
            productline = p.ProductLine__c;
            productId = p.Product__c;
            unit = p.Product__r.Unit__c;
            application = p.Product__r.ApplicableInstrumentModel__c;
    		productName = p.Product__r.ProductName__c == null ?  p.Product__r.Name:p.Product__r.ProductName__c ; // p.Product__r.Name;
    		spec = p.Product__r.Spec__c;
    		model = p.Product__r.Model__c;
    		serialNo = p.Product__r.SerialNo__c;
    		nccode = p.Product__r.NCCode__c;
    		brand = p.Product__r.Brand__c;

    		cate0 = p.Product__r.Category0__c;
    		cate1 = p.Product__r.Category1__c;
    		cate2 = p.Product__r.Category2__c;

    		productType = p.Product__r.TypeName__c;
            reason = p.QuotoReason__c ;
    		zl = p.Product__r.zl__c;
    		if(syspl!= null )sysPrice = syspl.Price__c;
    		if(pl != null )price = pl.Price__c;
    		adprice = p.AdjustSalesPrice__c;
            isFromsys = syspl != null;
            
    		if(pr == null )pr = new Price__c();
			taxrate  = pr.Taxrate__c;
			companyBottomPrice = pr.CompanyBottomPrice__c;
    			// areaDealerPrice = pr.AreaDealerPrice__c;
    			// instCost = pr.InstCost__c;
    			// invoiceDealerPrice = pr.InvoiceDealerPrice__c;
    			// hospitalManagerPrice = pr.HospitalManagerPrice__c;
    			// marketPrice = pr.MarketPrice__c;
       //          specialprice = pr.SpecialPrice__c;
       //          provincialAgencyPrice = pr.ProvincialAgencyPrice__c;
    		

            areaDealerPrice =isSys && MaccuraBrandUtil.maccura.contains(brand) ? p.Product__r.GroupRegionalDistributorsPrice__c :  pr.AreaDealerPrice__c;
            instCost =  pr.InstCost__c;
            invoiceDealerPrice = isSys && MaccuraBrandUtil.maccura.contains(brand) ? p.Product__r.GroupDeclarationDealerPrice__c : pr.InvoiceDealerPrice__c;
            hospitalManagerPrice =isSys && MaccuraBrandUtil.maccura.contains(brand) ? p.Product__r.GroupTerminalGuidePric__c :  pr.HospitalManagerPrice__c;
            marketPrice =isSys && MaccuraBrandUtil.maccura.contains(brand) ? p.Product__r.GroupMarketPrice__c :  pr.MarketPrice__c;
            specialprice = isSys && MaccuraBrandUtil.maccura.contains(brand) ? p.Product__r.GroupSpecialPrice__c : pr.SpecialPrice__c;
            provincialAgencyPrice =isSys && MaccuraBrandUtil.maccura.contains(brand) ? p.Product__r.GroupProvincialAgencyPrice__c :  pr.ProvincialAgencyPrice__c;
            
    		isHasLastMothPrice = ap!=  null;
    		if(ap != null )lastMothPrice = ap.AveragePrice__c;

    	}



    }
}